package de.goals.paulzerr;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class GoalsPageConnector extends AsyncTask<Map<String,String>, Void, JSONObject> {
	
	protected JSONObject doInBackground(Map<String,String>... p) {
		Map<String,String> params = p[0];
		String parameters = "";
		String url = "";	
		String result = "";
		JSONObject resultJSONObject = null;
		InputStream is = null;
		
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		if (params != null) {
			boolean firstParameter = true;
			for (String key : params.keySet()) {
				if(key.equals("url")){
					url = params.get(key);
				}
				
				if (firstParameter) {
					parameters += "?" + key + "=" + params.get(key).toString();
					firstParameter = false;
				} else {
					parameters += "&" + key + "=" + params.get(key).toString();
				}
			}
		}

		String urlWithParams = url + parameters;

		Log.i("urlWithParams", urlWithParams);
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(urlWithParams);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("Converting result",
					"Error converting result " + e.toString());
		}

		try {
			resultJSONObject = new JSONObject(result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return resultJSONObject;
	}



	

}


